<template>
  <div>
    <SettingTitle ref="settingTitleRef" :titlePlaceholder="$t('projectManage.projectType.new.typeTip')" :templateName="currentTemplateName" :templateColor="currentTemplateColor" :settingStep="settingStep" :currentTabComponent="currentTabComponent" @clickTab="handleClickTab" @handleChangeColor="changeColor" @handleInputTemplateName="inputTemplateName" @submit="handleSubmit" @back="checkModified(handleBack, true)" />

    <div class="project-type-con" v-loading="loading">
      <form-design ref="formDesign" v-model="fields" mode="projectType" :max="1000" v-if="currentTabComponent === 'project-fields-design'" :templateId="getTemplateId" :templateName="currentTemplateName"></form-design>
      <projectProcessDesign v-if="currentTabComponent === 'project-process-design'" :templateId="getTemplateId" ></projectProcessDesign>
      <projectAdvancedDesign v-if="currentTabComponent === 'project-advanced-design'" :templateId="getTemplateId" :templateName="currentTemplateName"></projectAdvancedDesign>

      <!-- <component :is="currentTabComponent" ref="sonRef" :templateId="getTemplateId" :fields="fields" :initFields="initFields"></component> -->
    </div>
  </div>
</template>
<script>
import { onMounted, reactive, toRefs, computed, ref } from 'vue';
import { settingStep } from '@src/modules/setting/projectManage/utils/index.js';

import SettingTitle from '@src/modules/setting/projectManage/components/SettingTitle.vue';
import projectAdvancedDesign from '@src/modules/setting/projectManage/projectManageTypeSetting/components/advancedDesign.vue';
import projectFieldsDesign from '@src/modules/setting/projectManage/projectManageTypeSetting/components/fieldsDesign.vue';
import projectProcessDesign from '@src/modules/setting/projectManage/projectManageTypeSetting/components/processDesign.vue';

import { MessageBox } from 'element-ui';
/* util */
import * as FormUtil from '@src/component/form/util';

import * as FormUtilValidate from '@src/mform/util/validate';

import { saveProjectTypeField, getProjectTypeName, getProjectTypeField } from '@src/api/ProjectManage.ts';
import i18n from '@src/locales';

import { toast, notification, openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';

import platform from '@src/platform';
export default {
  name: 'project-index',
  components: {
    SettingTitle,
    projectAdvancedDesign,
    projectFieldsDesign,
    projectProcessDesign,
  },
  provide:{
    setNeedLanguage:true
  },
  setup() {
    const settingTitleRef = ref();

    const state = reactive({
      currentTabComponent: 'project-fields-design',
      currentTemplateName: '',
      currentTemplateColor: '',
      loading: false,
      initFields: [], // 初始表单
      fields: []
    });

    // 获取路由参数
    const getParams = computed(() => {
      const searchParams = new URLSearchParams(location.search);
      const params = Object.fromEntries(searchParams.entries());
      return params;
    });

    // 获取模板id
    const getTemplateId = computed(() => {
      return getParams.value?.templateId || '';
    });

    // 切换模板
    const handleClickTab = name => {
      if (!checkFormName()) return;

      checkModified(() => {
        state.currentTabComponent = name.compName;
      });
    };

    /**
     * 校验表单名称
     */
    const checkFormName = () => {
      if (state.currentTemplateName.length == 0 || state.currentTemplateName === '' || state.currentTemplateName.trim().length == 0) {
        toast(i18n.t('projectManage.projectType.new.typeTip'), 'error');
        return false;
      }
      return true;
    };

    // 检查内容是否有修改
    const checkModifiedSon = () => {
      return JSON.stringify(state.fields) !== JSON.stringify(state.initFields);
    };

    /**
     * @description:检查当前tab页是否有修改
     * @param {*} bc 回调函数
     * @param {*} isReturn 是否是返回操作
     */
    const checkModified = (bc, isReturn) => {
      // 是否有更新
      let isModified = false;

      isModified = checkModifiedSon();

      let confirmObj = {
        content: isReturn ? i18n.t('event.setting.serviceEventTypeSetting.flow.tips1') : i18n.t('event.setting.serviceEventTypeSetting.flow.tips2'),
        confirmText: isReturn ? i18n.t('common.base.leave') : i18n.t('common.base.save'),
        cancelText: isReturn ? i18n.t('common.base.cancel') : i18n.t('common.base.notSaveForNow'),
      };

      if (!isModified) {
        bc();
        return;
      }

      MessageBox.confirm(confirmObj.content, i18n.t('common.base.toast'), {
        confirmButtonText: confirmObj.confirmText,
        cancelButtonText: confirmObj.cancelText,
        type: 'warning',
      })
        .then(async () => {
          if (!isReturn) await handleSubmit();
          bc();
        })
        .catch(err => {
          if (err !== 'cancel') return;
          // 取消
          if (isReturn) return;
          // 暂不保存 & 取消 - 数据恢复初始化
          state.fields = FormUtil.toFormField(state.initFields);

          bc();
        });
    };

    // 切换颜色
    const changeColor = newColor => {
      state.currentTemplateColor = newColor;
    };

    const inputTemplateName = val => {
      state.currentTemplateName = val;
    };

    // 获取名称&颜色
    const fetchProjectTypeName = () => {
      getProjectTypeName({
        typeId: getTemplateId.value,
        tableName: 'project',
      }).then(res => {
        const { success, message, data } = res;

        if (!success) return toast(message, 'error');

        state.currentTemplateName = data.name;
        state.currentTemplateColor = data.color;
      });
    };

    // 将字段转换成后端可接收的字段
    const packToField = origin => {
      let fields = FormUtil.toField(origin);

      fields = (fields || []).map((item, index) => {
        return {
          ...item,
          tableName: 'project',
          orderId: index,
          // 计划开始结束时间 yyyy-MM-dd
          setting: item.fieldName === 'planStartTime' || item.fieldName === 'planEndTime' ? { dateType: 'date' } : item.setting,
        }
      });

      return fields;
    };

    // 提交表单
    const submitField = async () => {
      try {
        let allFields = packToField(state.fields);

        // 表单字段格式校验
        let checkMessage = FormUtil.validate(allFields);
        if (!FormUtilValidate.notification(checkMessage)) return;

        settingTitleRef.value.pending = true;

        let ret = await saveProjectTypeField({
          templateId: getTemplateId.value,
          mouldName: 'project',
          name: state.currentTemplateName,
          color: state.currentTemplateColor,
          forms: allFields,
        });

        const { success, message } = ret;
        if (!success) {
          return toast(message, 'error');
        } else {
          notification({
            title: i18n.t('common.base.saveSuccess'),
            type: 'success',
          });

          fetchFields();
        }
      } catch (err) {
        console.log('error => submitField', err);
      } finally {
        settingTitleRef.value.pending = false;
      }
    };

    // 保存
    const handleSubmit = () => {
      if (!checkFormName()) return;

      submitField();
    };

    // 返回
    const handleBack = () => {
      let fromId = window.frameElement?.getAttribute('id');

      // 关闭当前tab
      let id = window?.frameElement?.dataset?.id;
      platform.closeTab(id);

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProjectManageTypeCartList,
        close: true,
        reload: true,
        fromId,
      });
    };

    // 获取表单字段
    const fetchFields = async () => {
      state.loading = true;
      try {
        let ret = await getProjectTypeField({
          templateId: getTemplateId.value,
          tableName: 'project',
        });

        const { success, data } = ret;
        if (!success) return toast(message, 'error');

        state.fields = FormUtil.toFormField(data);
        state.initFields = FormUtil.toFormField(data);
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.loading = false;
      }
    };

    onMounted(() => {
      fetchFields();
      fetchProjectTypeName();
    });

    return {
      settingTitleRef,
      ...toRefs(state),
      handleClickTab,
      settingStep,
      changeColor,
      inputTemplateName,
      getTemplateId,
      handleSubmit,
      checkModified,
      handleBack,
    };
  },
};
</script>
<style lang="scss" scoped>
.project-type-con {
  height: calc(100vh - 48px);
  padding: 12px;
}
</style>